/**
 * 连接异常通知服务
 * 当检测到连接异常时显示通知
 */
import { ref } from 'vue'
import { useConnectionMonitor, ConnectionStatus, getDisconnectReasonDescription } from './useConnectionMonitor'

// 通知配置
const notificationConfig = {
  enabled: true,
  showOnDisconnect: true,
  showOnReconnect: true,
  autoClose: true,
  autoCloseDelay: 5000 // 5秒后自动关闭
}

// 通知历史
const notificationHistory = ref([])

// 当前显示的通知
const activeNotifications = ref([])

/**
 * 初始化连接通知
 */
export function useConnectionNotification() {
  const {
    onConnectionChange
  } = useConnectionMonitor()

  // 监听连接状态变化
  const unsubscribe = onConnectionChange((data) => {
    handleConnectionNotification(data)
  })

  /**
   * 显示通知
   */
  function showNotification(title, message, type = 'info') {
    if (!notificationConfig.enabled) return

    const notification = {
      id: Date.now(),
      title,
      message,
      type, // 'info', 'warning', 'error', 'success'
      timestamp: new Date().toISOString(),
      visible: true
    }

    // 添加到活动通知列表
    activeNotifications.value.push(notification)

    // 添加到历史记录
    notificationHistory.value.unshift(notification)
    if (notificationHistory.value.length > 50) {
      notificationHistory.value = notificationHistory.value.slice(0, 50)
    }

    // 自动关闭
    if (notificationConfig.autoClose) {
      setTimeout(() => {
        closeNotification(notification.id)
      }, notificationConfig.autoCloseDelay)
    }

    // 打印到控制台
    console.log(`🔔 [Notification] ${title}: ${message}`)

    return notification
  }

  /**
   * 关闭通知
   */
  function closeNotification(id) {
    const index = activeNotifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      activeNotifications.value.splice(index, 1)
    }
  }

  /**
   * 关闭所有通知
   */
  function closeAllNotifications() {
    activeNotifications.value = []
  }

  /**
   * 获取通知历史
   */
  function getNotificationHistory(limit = 10) {
    return notificationHistory.value.slice(0, limit)
  }

  /**
   * 清除通知历史
   */
  function clearNotificationHistory() {
    notificationHistory.value = []
  }

  /**
   * 设置通知配置
   */
  function setNotificationConfig(config) {
    Object.assign(notificationConfig, config)
  }

  return {
    activeNotifications,
    notificationHistory,
    showNotification,
    closeNotification,
    closeAllNotifications,
    getNotificationHistory,
    clearNotificationHistory,
    setNotificationConfig,
    unsubscribe
  }
}

/**
 * 处理连接通知
 */
function handleConnectionNotification(data) {
  const { type, status, reason_code, reason_text } = data

  const typeName = type === 'md' ? '行情' : '交易'

  if (status === ConnectionStatus.DISCONNECTED) {
    if (notificationConfig.showOnDisconnect) {
      const reasonDesc = reason_text || getDisconnectReasonDescription(reason_code)
      
      // 显示断线通知
      showConnectionNotification(
        `${typeName}连接断开`,
        `${typeName}连接已断开：${reasonDesc}`,
        'error'
      )

      // 同时在控制台输出详细信息
      console.error(`❌ [ConnectionNotification] ${typeName}连接断开`, {
        reason_code,
        reason_text: reasonDesc,
        timestamp: new Date().toISOString()
      })
    }
  } else if (status === 'login_success' || status === ConnectionStatus.CONNECTED) {
    if (notificationConfig.showOnReconnect) {
      // 显示登录/连接成功通知
      showConnectionNotification(
        `${typeName}连接成功`,
        `${typeName}已成功连接`,
        'success'
      )

      console.log(`✅ [ConnectionNotification] ${typeName}连接成功`)
    }
  } else if (status === 'login_failed') {
    if (notificationConfig.showOnDisconnect) {
      // 显示登录失败通知
      showConnectionNotification(
        `${typeName}登录失败`,
        `${typeName}登录失败：${reason_text || '未知错误'}`,
        'error'
      )

      console.error(`❌ [ConnectionNotification] ${typeName}登录失败:`, reason_text)
    }
  }
}

/**
 * 显示连接通知（内部辅助函数）
 */
function showConnectionNotification(title, message, type) {
  const notification = {
    id: Date.now(),
    title,
    message,
    type,
    timestamp: new Date().toISOString(),
    visible: true
  }

  // 添加到活动通知列表
  activeNotifications.value.push(notification)

  // 添加到历史记录
  notificationHistory.value.unshift(notification)
  if (notificationHistory.value.length > 50) {
    notificationHistory.value = notificationHistory.value.slice(0, 50)
  }

  // 自动关闭
  if (notificationConfig.autoClose) {
    setTimeout(() => {
      const index = activeNotifications.value.findIndex(n => n.id === notification.id)
      if (index > -1) {
        activeNotifications.value.splice(index, 1)
      }
    }, notificationConfig.autoCloseDelay)
  }
}
